<?php
/**
 * 分类模型管理
 * @author cjli
 *
 */
class CategoryModel extends Model
{
	const TYPE_CATEGORY = 1; //产品分类
	const TYPE_ARTICLE = 2; //文章分类
  	const TYPE_BRAND = 3; //品牌分类
  	const TYPE_ARTICLE_RECOMMEND = 4; //文章推荐分类
  	const TYPE_RECOMMEND = 5; //产品推荐分类
	const TYPE_PROBLEM_TYPES = 6; //问题类型分类
	const TYPE_PRODUCTION = 7; //作品分类
	const TYPE_STYLE = 8; //作品分类
	const TYPE_COLOUR = 9; //颜色
	const TYPE_complaint = 10; //投诉类型
	const TYPE_PRODUCT_COLOUR = 11; //产品颜色
  
	protected $_validate=array(
		array('name','','分类名称已经存在！',1,'unique',1),
	);
	protected $_auto=array(
		array('lastorder','int',1,'function'),
	);
	
	public $vocabularyType = array(
    self::TYPE_CATEGORY => 'category',
    self::TYPE_ARTICLE => 'article',
    self::TYPE_BRAND => 'brand',
    self::TYPE_ARTICLE_RECOMMEND => 'article_recommend',
    self::TYPE_RECOMMEND => 'recommend',
	self::TYPE_PROBLEM_TYPES => 'problem_types',
	self::TYPE_PRODUCTION => 'production',
  );
	/**
   * 获取所有分类信息列表
   * @return object 分类列表信息
   */
  public static function getVocabularyList()
  {
  	$category = array();
		if(S('admin_vocabulary_list')){
			$category = S('admin_vocabulary_list');
		}else{
			$vocabularydb = D('vocabulary');
			$result = $vocabularydb->select();
			foreach ($result as $key =>$val){
				$category[$val['id']] = $val['name'];
			}
			S('admin_vocabulary_list', $category);
		}
		return $category;
  }
	
	/**
	 * 获取全部分类
	 * @param int $vid 类型ID号
	 */
	public static function getCategoryList( $vid = self::TYPE_CATEGORY)
	{
		$where = array(
			'vid'=>$vid,
			'language_id' => C('language_id'),
		);
			$catdb = D('category');
			$catdb->field('category.id,category.parentid,category.display,category.listorder,category.model_id,ci.name');
			$catdb->join('category_items AS ci ON ci.category_id = category.id');
			if($vid == self::TYPE_BRAND){
				$catdb->order('ci.name ASC');
			}else{
				$catdb->order('category.listorder DESC, category.id DESC');
			}
			$category = $catdb->where($where)->select();
			//dump($category);exit;
		return $category;
	}
	
	/**
	 * 简单分类列表
	 * @param int $vid 类型ID
	 */
	public static function getCategoryListBase($vid = self::TYPE_CATEGORY)
	{
		$category = array();
		if(S('admin_category_list_base_'.$vid)){
			$category = S('admin_category_list_base_'.$vid);
		}else{
			$where = array(
				'vid'=>$vid,
				'language_id' => C('language_id'),
				//'display' => 1,
			);
			$catdb = D('category');
			$catdb->field('category.id,category.parentid,ci.name');
			$catdb->join('category_items AS ci ON ci.category_id = category.id');
			if($vid == self::TYPE_BRAND){
				$catdb->order('ci.name ASC');
			}else{
				$catdb->order('category.listorder DESC, category.id DESC');
			}
			$category = $catdb->where($where)->select();
			S('admin_category_list_base_'.$vid, $category);
		}
		return $category;
	}
	
	/**
	 * 树型下拉选择分类
	 * @param int $selectid 选择中的ID号
	 * @param int $vid 类型ID
	 */
	public static function categorySelectList($selectid = 0, $vid = self::TYPE_CATEGORY)
	{
		$category = self::getCategoryListBase($vid);
		import('COM.Tree');
		$tree = new Tree();
		$array = array();
		foreach($category as $r) {
			$r['selected'] = $r['id'] == $selectid ? 'selected' : '';
			$array[] = $r;
		}
		$str  = "<option value='\$id' \$selected>\$spacer \$name</option>";

		$tree->init($array);
		$select_categorys = $tree->get_tree(0, $str);
		return $select_categorys;
	}
	
	/**
	 * 分类信息入库
	 * @param array $post post数据
	 * @param int $category_id 分类ID
	 */
	public static function updateCategoryInfo($post, $category_id = null)
	{
		$catdb = D('category');
		$data = array(
			'vid' => intval($post['vid']),
			'parentid' => intval($post['parentid']),
			'model_id' => intval($post['model_id']),
			'path_alias' => $post['path_alias'] ? trim($post['path_alias']) : null,
			'template' => $post['template'] ? trim($post['template']) : null,
			'img' => $post['img'] ? trim($post['img']) : null,
			'adv_img' => $post['adv_img'] ? trim($post['adv_img']) : null,
			'display' => intval($post['display']),
			'listorder' => intval($post['listorder']),
			'filter_attr'  => !empty($post['filter_attr'])  ? implode(',', array_unique(array_diff($post['filter_attr'],array(0)))) : 0,
			'category_id'  => !empty($post['categoryId'])  ? implode(',', array_unique(array_diff($post['categoryId'],array(0)))) : 0,
			'colour_id'  => !empty($post['colourId'])  ? implode(',', array_unique(array_diff($post['colourId'],array(0)))) : 0,
            'is_3d' => $post['is_3d'] ? trim($post['is_3d']) : 0,
		);
		
		if($category_id){
			$catdb->where(array('id' => $category_id))->save($data);
		}else{
			$category_id = $catdb->add($data);
		}
		
		S('admin_category_list_base_'.intval($post['vid']), NULL);
		S('category_child_ids_'.$category_id, NULL);
		return $category_id;
	}
	
	/**
	 * 分类详细信息入库
	 * @param array $post post数据
	 * @param int $category_id 分类ID
	 */
	public static function updateCategoryItems($post, $category_id)
	{
		if(!intval($category_id)) return false;
		$category_items_db = D('category_items');
		//清空原数据
		$category_items_db->where(array('category_id' => $category_id))->delete();
		//语言列表
		$languageList = SiteModel::getLanguageList();
		foreach($languageList as $language_id => $language_name){
			if($post[$language_id]['name']){
				$data = array(
					'category_id' => $category_id,
					'language_id' => $language_id,
					'name' => trim($post[$language_id]['name']),
					'summary' => trim($post[$language_id]['summary']),
					'description' => trim($post[$language_id]['description']),
					'meta_title' => trim($post[$language_id]['meta_title']),
					'meta_keywords' => trim($post[$language_id]['meta_keywords']),
					'meta_description' => trim($post[$language_id]['meta_description']),
					'items_img' => trim($post[$language_id]['items_img']),
					'items_adv_img' => trim($post[$language_id]['items_adv_img']),					
				);
				$category_items_db->add($data);
			}
		}
	}
	
	/**
	 * 获取分类的多语言详细信息
	 * @param int $category_id 分类ID
	 * @param int $language_id 语言ID号
	 */
	public static function getCategoryItems($category_id, $language_id = 0)
	{
		$where['category_id'] = $category_id;
		if($language_id){
			$where['language_id'] = $language_id;
		}
		$catItemsArray = array();
		$category_items_db = D('category_items');
		$cate_itmes_list = $category_items_db->where($where)->select();
		if($cate_itmes_list){
			foreach ($cate_itmes_list as $cat){
				$catItemsArray[$cat['language_id']] = $cat;
			}
		}
		return $catItemsArray ? $catItemsArray : false;
	}
	
	/**
	 * 删除分类
	 * @param int $category_id 分类ID
	 */
	public static function deleteCategory($category_id)
	{
		$catdb = D('category');
		$catInfo = $catdb->find($category_id);
		if(!$catInfo) return false;
		
		//删除分类关联
		$vid = $catdb->where('id='.$category_id)->getField('vid');
		//文章分类
		if($vid == self::TYPE_ARTICLE){
			$article_db = D('article');
			$article_db->where('catid='.$category_id)->save(array('catid' => 0));
		}
		//文章推荐分类
		elseif($vid == self::TYPE_ARTICLE_RECOMMEND){
			$article_cat_db = D('category_article');
			$article_cat_db->where('catid='.$category_id)->delete();
		}
		//商品分类
		elseif($vid == self::TYPE_CATEGORY){
			$product_db = D('product');
			$product_db->where('catid='.$category_id)->save(array('catid' => 0));
		}
		//品牌
		elseif($vid == self::TYPE_BRAND){
			$product_db = D('product');
			$product_db->where('catid='.$category_id)->save(array('brand_id' => 0));
		}
		//其他分类
		else{
			$product_cat_db = D('category_product');
			$product_cat_db->where('catid='.$category_id)->delete();
		}
		
		//删除分类详细
		$category_items_db = D('category_items');
		$category_items_db->where(array('category_id' => $category_id))->delete();
		//删除分类表
		$catdb->delete($category_id);
		
		//删除缓存
		S('category_child_ids_'.$category_id, NULL);
		S('admin_category_list_base_'.$vid, NULL);
		
		$languageList = SiteModel::getLanguageList();
		foreach ($languageList as $language_id => $language_name){
			$cache_id = 'category_list_base_'.$vid.'_'.$language_id;
			S($cache_id, NULL);
		}
	}
	
	/**
	 * 获取分类的所有子类一维数组
	 * @param unknown_type $cid 当前分类ID
	 * @param unknown_type $vid 类型ID
	 * @return string
	 */
	public static function getCategoryChildArray($cid=0, $vid=self::TYPE_CATEGORY)
	{
		$categorys = array();
		$categoryList = self::getCategoryListBase($vid);
		if(is_array($categoryList)){
			require_cache(EXTEND_PATH.'Function/extend.php');
			$categorys = list_to_tree($categoryList, 'id', 'parentid', 'children', $cid);
		}
		return $categorys ? $categorys : false;
	}
	
	/**
	 * 获取分类的所有子类ID
	 * @param int $catid 分类ID
	 * @param int $vid 类型ID
	 * @return string
	 */
	public static function getCategoryChildIds($cid=0, $vid=self::TYPE_CATEGORY)
	{
		$cacheId = 'category_child_ids_'.$cid;
		$catIds = '';
		if(S($cacheId)){
			$catIds = S($cacheId);
		}else{
			$ids = '';
			$categorys = self::getCategoryChildArray($cid, $vid);
			if($categorys){
				foreach ($categorys as $cat){
					$ids[] = $cat['id'];
				}
			}
			$ids[] = $cid;
			$catIds = join(',', $ids);
			S($cacheId, $catIds);
		}
		return $catIds;
	}
	
	/**
	 * 单个分类详情
	 * @param int $vid 类型ID
	 */
	public static function getCategoryInfo($id=0, $language_id=NULL)
	{
		$category = array();
	    if(!$language_id) $language_id = C('language_id');
		$catdb = D('category');
		$where = array(
			'id'=>$id,
			'language_id' => $language_id,
			'display' => 1,
		);
		$catdb->field('category.id,category.parentid,ci.name');
		$catdb->join('category_items AS ci ON ci.category_id = category.id');
		$category = $catdb->where($where)->find();
			
		return $category;
	}

	
	/**
	 * 返回分类的父ID
	 * @param int $catid 分类ID
	 * return int $parentid
	 */
	public static function get_category_parentid($cid)
	{
        $catdb = D('category');
		$catdb->where(array('id' => $cid)); 
		$parentid = $catdb->getField('parentid');      
        return $parentid;
	}
}